const Router = require("koa-router");
const { TokenValidator,NotEmptyValidator } = require("../../validator/validator");
const { User } = require("../../../models/user");
const { Wx } = require("../../../models/wx");
const {Auth} = require('../../../middlewares/auth'); 
const { generateToken } = require("../../../core/util");
const {ScopeType} = require('../../../lib/enum');
const { LoginType } = require("../../../lib/enum");

const router = new Router({ prefix: "/v1/token" });

router.post("/", async (ctx, next) => {
  const v = await new TokenValidator().validate(ctx);

  switch (v.get("body.type")) {
    case LoginType.USER_EMAIL:
      const res = await emailLogin(v.get("body.account"), v.get("body.password"));
      ctx.body={
          token:res,
      }
      break;

    case LoginType.USER_MINI_PROGRAM:
      const data = await wxMiniProgramLogin(v.get("body.account"))

      
      ctx.body = {
        code:200,
        data,
        success:true
      }
      break;
    default:
      break;
  }

  //   throw new global.errs.Success()
});


router.post('/verify',async (ctx,next)=>{
  const v= await new NotEmptyValidator().validate(ctx)
  const res = await Auth.verifyToken(v.get("header.token"))
  throw new global.errs.Success()

})

async function emailLogin(account, secret) {
  const user = await User.validateEmailLoin(account, secret);
  const token = generateToken(user.id,ScopeType.USER)
  return token
}

async function wxMiniProgramLogin(code){
  const user  = await Wx.code2Session(code)
  const token = generateToken(user.id,ScopeType.USER)
  return {
    user:{
      id:user.id,
      openId:user.openId,
      nickName:user.nickname
    },
    token
  }
}

module.exports = router;
